# from rest_framework import serializers
# from book.models import BookInfo
# class BookInfoSerializers(serializers.Serializer):
#     """图书数据序列化器具"""
#     id = serializers.IntegerField(read_only=True) # read_only 只在序列化的时候出现此字段
#     name = serializers.CharField(write_only=True,max_length=10,min_length=5)
#     pub_date = serializers.DateField(required=True)
#     readcount = serializers.IntegerField(max_value=100,min_value=1)
#
#
#
#
# class PeopleInfoSerializers(serializers.Serializer):
#     id = serializers.IntegerField()
#     name = serializers.CharField()
#     password = serializers.CharField()
#     description = serializers.CharField()
#     is_delete = serializers.BooleanField()

# ***************************

from rest_framework import serializers
from book.models import BookInfo


class BookInfoSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(write_only=True, max_length=10, min_length=5)
    pub_date = serializers.DateField(required=True)
    readcount = serializers.IntegerField(required=False)
    commentcount = serializers.IntegerField(required=False)

    def validate_readcount(self, value):
        """单个字段验证"""
        if value < 0:
            # raise Exception('阅读量不能为负数')
            raise serializers.ValidationError('阅读量不能为负数')
        return value

    def validate(self, data):
        """多个字段验证"""
        readcount = data.get('readcount')
        commentcount = data.get('commentcount')

        if commentcount > readcount:
            raise serializers.ValidationError('阅读量不能大于评量')

        return data

    def create(self, validated_data):
        """保存数据 新增"""
        # 验证没问题保存数据
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """修改数据"""
        instance.name = validated_data.get('name', instance.name)
        instance.pub_date = validated_data.get('pub_date', instance.pub_date)
        instance.readcount = validated_data.get('readcount', instance.readcount)
        instance.commentcount = validated_data.get('commentcount', instance.commentcount)
        # 数据入库
        instance.save()
        return instance


# ***************************
"""模型类序列化器ModelSerializer"""


class BookInfoModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        # 所有字段
        # fields = '__all__'

        # 除image之外的所有字段
        # exclude = ('image',)

        # 指定字段
        fields = ('id', 'name', 'readcount')

        # 设置只读字段
        read_only_fields = ('id', 'name')

        # 为字段添加或修改参数

        extra_kwargs = {
            'readcount': {
                'required': True
            }
        }


# ************************************
# 反序列化进阶使用
# from rest_framework import serializers
from book.models import PeopleInfo, BookInfo
# class PeopleInfoModelSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = PeopleInfo
#         fields = ['id','book','name','password']
#         extra_kwargs = {
#             'password': {'write_only': True} #表明该字段仅用于反序列化输入。在序列化输出时忽略该字段。
#         }
#
# class BookModelSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = BookInfo
#         fields = '__all__'


# *****************************************
# book外键

# from book.models import PeopleInfo, BookInfo
#
#
# class PeopleInfoModelSerializer(serializers.ModelSerializer):
#     # book_id = serializers.IntegerField()
#
#     # book_id = serializers.IntegerField(required=False)
#     # book = serializers.StringRelatedField()
#
#     book = serializers.PrimaryKeyRelatedField(queryset=BookInfo.objects.all())
#     class Meta:
#         model = PeopleInfo
#         fields = ['id', 'book_id', 'book','name', 'password']
#         extra_kwargs = {
#             'password': {'write_only': True}  # 表明该字段仅用于反序列化输入。在序列化输出时忽略该字段。
#         }
#
#
# class BookModelSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = BookInfo
#         fields = '__all__'


# *****************************************************

# from book.models import PeopleInfo, BookInfo
#
#
# class PeopleInfoModelSerializer(serializers.ModelSerializer):
#     # book_id = serializers.IntegerField()
#
#     book_id = serializers.IntegerField(required=False)
#     book = serializers.StringRelatedField()
#
#     # book = serializers.PrimaryKeyRelatedField(queryset=BookInfo.objects.all())
#
#     class Meta:
#         model = PeopleInfo
#         fields = ['id', 'book_id', 'book', 'name', 'password','is_delete','description']
#         extra_kwargs = {
#             'password': {'write_only': True},  # 表明该字段仅用于反序列化输入。在序列化输出时忽略该字段。
#             'is_delete': {'read_only': True}   # 表明该字段仅用于序列化输出。反序列化时忽略次字段。
#         }
#
#
# class BookModelSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = BookInfo
#         fields = '__all__'


# ********************************
#  一对多
from book.models import PeopleInfo, BookInfo


class PeopleInfoModelSerializer(serializers.ModelSerializer):
    # book_id = serializers.IntegerField()

    book_id = serializers.IntegerField(required=False)
    book = serializers.StringRelatedField()

    # book = serializers.PrimaryKeyRelatedField(queryset=BookInfo.objects.all())

    class Meta:
        model = PeopleInfo
        fields = ['id', 'book_id', 'book', 'name', 'password', 'is_delete', 'description']
        extra_kwargs = {
            'password': {'write_only': True},  # 表明该字段仅用于反序列化输入。在序列化输出时忽略该字段。
            'is_delete': {'read_only': True}  # 表明该字段仅用于序列化输出。反序列化时忽略次字段。
        }


class BookModelSerializer(serializers.ModelSerializer):
    people = PeopleInfoModelSerializer(many=True)

    class Meta:
        model = BookInfo
        fields = '__all__'

    # 重写create方法
    def create(self, validated_data):

        people = validated_data.pop('people')
        book = BookInfo.objects.create(**validated_data)

        for person in people:
            PeopleInfo.objects.create(book=book, **person)

        return book